#!/bin/sh

# Save the list of currently staged files
STAGED_FILES=$(git diff --cached --name-only)

# Check for staged files with unstaged modifications
MODIFIED_FILES=$(git diff --name-only)

# Find files that overlap between staged and modified without using process substitution
CONFLICTING_FILES=""
for file in $STAGED_FILES; do
  if echo "$MODIFIED_FILES" | grep -qx "$file"; then
    CONFLICTING_FILES="$CONFLICTING_FILES$file\n"
  fi
done

# Abort if there are conflicts
if [ -n "$CONFLICTING_FILES" ]; then
  echo "Error: The following staged files have unstaged modifications, which can cause issues with the pre-commit eslint fix and prettier rewrite execution:"
  echo -e "$CONFLICTING_FILES" # Use -e for newline interpretation in echo
  echo "Please stage the changes or reset them before committing."
  echo "If this is a temporary local commit, you can also use the --no-verify flag to bypass the pre-commit test and linting. i.e. 'git commit --no-verify'"
  exit 1 # Abort commit
fi

# Run tests and linting
npm test
npm run lint

# Re-stage files after lint fixes (only staged files)
# Use a portable alternative for xargs
echo "$STAGED_FILES" | while IFS= read -r file; do
  if [ -f "$file" ]; then
    git add "$file"
  fi
done
